package com.warrior.superdata.service.impl;

import com.warrior.superdata.enums.ConditionType;
import com.warrior.superdata.mysql.entity.dto.ApiParamDto;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Description:
 * @ClassName: EsQueryHelpService.java
 * @date: 2022/6/28 14:40
 * @author xujian
 */
public class EsQueryHelpService {

    public static BoolQueryBuilder generateQuery(List<ApiParamDto> params) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (!CollectionUtils.isEmpty(params)) {
            params.forEach(param -> {
                if (null == param.getIsUpdate() || 1 != param.getIsUpdate()) {
                    String paraTableField = param.getParamTableFieldName().split("\\.")[1];
                    if (ConditionType.EQ.getType() == param.getConditionType()) {
                        boolQueryBuilder.must(QueryBuilders.termQuery(paraTableField, param.getParamValue()));
                    } else if (ConditionType.GE.getType() == param.getConditionType()) {
                        boolQueryBuilder.must(QueryBuilders.rangeQuery(paraTableField).gt(param.getParamValue()));
                    } else if (ConditionType.GEQ.getType() == param.getConditionType()) {
                        boolQueryBuilder.must(QueryBuilders.rangeQuery(paraTableField).gte(param.getParamValue()));
                    } else if (ConditionType.LE.getType() == param.getConditionType()) {
                        boolQueryBuilder.must(QueryBuilders.rangeQuery(paraTableField).lt(param.getParamValue()));
                    } else if (ConditionType.LEQ.getType() == param.getConditionType()) {
                        boolQueryBuilder.must(QueryBuilders.rangeQuery(paraTableField).lte(param.getParamValue()));
                    } else if (ConditionType.LIKE.getType() == param.getConditionType()) {
                        boolQueryBuilder.must(QueryBuilders.wildcardQuery(paraTableField, "*" + param.getParamValue() + "*"));
                    }
                }
            });
        }
        return boolQueryBuilder;
    }

}
